<!-- eslint-disable no-undef -->
<!-- 系统软件，新建文档  -->
<template>
  <div class="page-wrap createCss" v-loading="Data.isLoading">
    <Anthor
      :offset="100"
      :target="'.createBox'"
      :tabList="route.query.oid ? Data.anthorList.slice(1) : Data.anthorList"
      :actived="Data.activedStr"
    >
      <template #title>
        <div class="create_title" v-if="!route.query.oid">{{ route.meta.title }}</div>
        <div class="create_title" v-else>
          {{ info.typeNameDisplay }} - {{ info.displayIdentifier }}
        </div>
      </template>
    </Anthor>
    <div class="createBox">
      <div class="depart" id="types" v-if="!route.query.oid">
        <div class="title">类型</div>
        <el-row>
          <el-col :span="12">
            <el-form-item label="文档大类" :required="true">
              <el-select v-model="info.fileType" style="width: 100%" @change="getFileType">
                <el-option
                  v-for="(item, index) in Data.fileTypeList"
                  :key="index"
                  :value="item.value"
                  :label="item.label"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
      <div class="depart" id="mainContent">
        <div class="title">主要内容源</div>
        <div class="mainContent_upload" v-if="info.fileType">
          <div style="margin-left: 10px; margin-bottom: 10px">文件</div>
          <uploadContent
            @onUpload="onUpload"
            @delFile="delFile"
            v-model:fileLists="Data.contentFile"
          ></uploadContent>
        </div>
      </div>
      <div class="depart" id="attribute">
        <div class="title">属性</div>
        <Form
          ref="form"
          labelWidth="200px"
          :formList="Data.formList"
          :submitData="Data.submitData"
        ></Form>
      </div>
      <div class="depart mb70" id="setFile">
        <div class="title">设置附件</div>
        <div class="btn_box">
          <el-button @click="openUpload" type="primary">上传</el-button>
          <el-button @click="delUpload">删除</el-button>
        </div>
        <PiTable
          :columns="Data.affectColumns"
          :data="Data.affectData"
          :pagination="false"
          :isShowSetting="false"
          :selectable="true"
          @selectionChange="selectionChange"
        >
          <template #description="scope">
            <el-input
              v-model="scope.row.description"
              @change="onChange($event, scope.row)"
            ></el-input>
          </template>
        </PiTable>
      </div>
    </div>

    <div class="footer">
      <div class="actionRow">
        <el-button @click="goback">
          {{ $intl('btn.cancel').d('取消') }}
        </el-button>
        <el-button v-if="route.query.oid" @click="onSubmit(true)" :loading="Data.isLoading">
          {{ '保存' }}
        </el-button>
        <el-button @click="onSubmit(false)" type="primary" :loading="Data.isLoading">
          {{ $intl('btn.submit').d('提交') }}
        </el-button>
      </div>
    </div>
  </div>
  <div>
    <uploadDialog
      :isSingleUpload="true"
      :isShow="Data.isDialogShow"
      @close="close"
      @submit="submit"
    ></uploadDialog>
  </div>
</template>

<script setup>
import uploadContent from './components/uploadContent.vue';
// import productDialog from '../components/productDialog.vue';
import { findIndexes } from '@/utils/utils';

const router = useRouter();
const route = useRoute();
const { proxy: that } = getCurrentInstance();
const $api = window.$api;
const Data = reactive({
  isNotCheckIn: false, // 点保存的时候为true
  activedStr: 'types',
  isLoading: false,
  isDialogShow: false,
  formList: [],
  submitData: {},
  userInfo: JSON.parse(window.$Cookies.get('userInfo')),
  fileTypeList: [],
  // 锚点
  anthorList: [
    { label: '类型', id: 'types' },
    { label: '主要内容源', id: 'mainContent' },
    { label: '属性', id: 'attribute' },
    { label: '设置附件', id: 'setFile' },
  ],
  // 上传附件表头
  affectColumns: [
    { title: '附件名称', dataIndex: 'name' },
    { title: '附件说明', dataIndex: 'description' },
  ],
  // 上传附件数据
  affectData: [],
  picRules: {
    required: true,
    message: '必填',
    // trigger: 'change',
  },
  contentFile: [], // 主要内容
  selectFiles: [], // 勾选的表格附件数据
  fileList: [], // 上传的附件文件
  containerOid: '', // 容器oid
  projectNumber: '', // 项目编号
});
const form = ref();
const info = reactive({
  fileType: undefined,
  version: '',
  typeNameDisplay: '',
  displayIdentifier: '',
});
onActivated(() => {
  _getDocTypes('系统软件库', route.query.oid);
  let oid = route.query.oid;
  if (oid) {
    Data.isLoading = true;
    _getEditInfoLayout(oid);
    _getConteneFile(oid);
    _getFiles(oid);
  } else {
    // clearData();
  }
});

onMounted(() => {
  clearData();
  // if (route.name === !'createSystemFile') {
  //   Data.projectNumber = JSON.parse(sessionStorage.getItem('projectRow'))?.projectShortName;
  // }
  Data.containerOid = sessionStorage.getItem('containerOid');
  scrollFun();
});

/**
 * 滚轮事件
 */
const createRef = ref();
const scrollFun = () => {
  document.getElementsByClassName('createBox')[0].addEventListener('scroll', () => {
    const parentTop = document.getElementsByClassName('createBox')[0].scrollTop;
    parentTop < 31 && (Data.activedStr = 'types');
    parentTop > 31 && (Data.activedStr = 'mainContent');
    parentTop > 200 && (Data.activedStr = 'attribute');
  });
};

// 获取文档大类
const _getDocTypes = async (containerName, oid) => {
  await $api.documentApi.getDocType().then((res) => {
    if (res.success) {
      for (let key in res.data) {
        Data.fileTypeList.push({
          value: key,
          label: res.data[key],
        });
      }
    }
  });
  if (!oid) return;
  let params = new FormData();
  params.append('serviceKey', 'default');
  params.append('oid', oid);
  $api.commonApi.getObjInfo(params).then((res) => {
    if (res.success) {
      info.fileType = res.data.typeName;
      info.version = res.data.version;
      info.typeNameDisplay = res.data.typeNameDisplay;
      info.displayIdentifier = res.data.displayIdentifier;
    }
  });
};

/**
 * 产品型号弹出框
 */
const productDialogConfirm = (val, option) => {
  option.displayValue = val;
  option.value = val;
  Data.submitData[option.name] = val;
  option.showDialog = false;
};
// 只有 A 版本，名称可以编辑
const setNameReadonly = (val) => {
  Data.formList.forEach((item) => {
    const curr = item.list.find((attr) => attr[0].name === 'name');
    curr && (curr[0].readOnly = !val.startsWith('A'));
    if (item.groupName === '属性') {
      item.items = item.items.map((v) => {
        return {
          ...v,
          readOnly: v.name === 'name' ? !val.startsWith('A') : v.readOnly,
        };
      });
    }
  });
};
// 获取编辑文档的布局
const _getEditInfoLayout = async (editOid) => {
  let params = {
    serviceKey: 'default',
    oid: editOid,
  };
  let layoutObj = await that.$commonApisFun.getEditLayoutData(params);
  Data.submitData = layoutObj.submitData;
  Data.formList = layoutObj.formList;
  Data.isLoading = false;
};
// watch(() => Data.version, setNameReadonly);
// 获取主内容文件
const _getConteneFile = async (oid) => {
  let params = new FormData();
  params.append('oid', oid);
  params.append('type', 'PRIMARY');
  await $api.commonApi.getFileServer(params).then((res) => {
    if (res.success === true) {
      Data.contentFile = res.data.map((item) => ({
        name: item.name,
        size: item.size,
        uid: new Date(item.modifyStamp).getTime(),
        oid: item.oid,
      }));
      console.log(Data.contentFile, '主内容文件');
    }
  });
};

// 附件的描述
const onChange = ($event, row) => {
  Data.affectData.forEach((e) => {
    if (e.oid === row.oid) {
      e.description = $event;
    }
  });
};

// 获取附件文件
const _getFiles = async (oid) => {
  let params = new FormData();
  params.append('oid', oid);
  params.append('type', 'SECONDARY');
  await $api.commonApi.getFileServer(params).then((res) => {
    if (res.success === true) {
      Data.affectData = res.data;
    }
  });
};
const initFun = async (val) => {
  Data.isLoading = true;
  // 获取表单
  let params = {
    serviceKey: 'wt.doc.WTDocument',
    softType: info.fileType,
  };
  let layoutObj = await $api.commonApi.getCreateLayout(params);
  // layoutObj.submitData['projectNumber'] = Data.projectNumber;
  // layoutObj.submitData['ProjectNumber'] = Data.projectNumber;
  Data.formList = [];
  Data.submitData = {};
  layoutObj.data.forEach((item) => {
    const rows = Array.from(new Set(item.items.map((el) => el.row)));
    const list = [];
    rows.forEach((row) => {
      const arr = item.items.filter((el) => el.row === row);
      list.push(arr);
    });
    Data.formList.push({
      groupName: item.groupName,
      list,
    });
    item.items.forEach((el) => {
      Data.submitData[el.name] = item.vlue;
    });
  });
  // Data.formList = layoutObj.data;
  /**从项目进入渲染项目编号 GDprojectNo*/
  if (route.query.entry) {
    let projectRows = JSON.parse(sessionStorage.getItem('projectRow'));
    Data.submitData['GDprojectNo'] = projectRows.projectShortName;
    if (val === 'com.sfdomain.DevelopDesignRecords') {
      Data.submitData['projectNumber'] = projectRows.projectShortName;
    } else {
      Data.submitData['ProjectNumber'] = projectRows.projectShortName;
    }
    Data.submitData['ProductSeries'] = projectRows.Product;
  }
  Data.isLoading = false;
};

// 打开上传附件弹窗
const openUpload = () => {
  Data.isDialogShow = true;
};

// 删除附件
const delUpload = () => {
  let ss = Data.selectFiles.map((e) => {
    return e.uid;
  });
  let newArr = Data.affectData.filter((e) => {
    return !ss.includes(e.uid);
  });
  Data.affectData = newArr;
};

// 删除主内容
const delFile = () => {
  Data.contentFile = [];
};

// 上传主要内容
const onUpload = (file) => {
  const lineIndexs = findIndexes(file.name, '.');
  //   const prefix = ['源代码', '固化文件'];
  let name = file.name.substring(0, lineIndexs[lineIndexs.length - 1]);
  file.name = name;
  Data.contentFile = [file];
  //   prefix.forEach((item) => {
  //     if (info.typeNameDisplay === item && !name.startsWith(item)) {
  //       name = item + '_' + name;
  //     }
  //   });
  Data.submitData['name'] = name;
};

// 取消附件弹窗
const close = (e) => {
  Data.isDialogShow = e;
};

// 勾选附件
const selectionChange = (row) => {
  Data.selectFiles = row;
};

const submit = (fileList) => {
  fileList.forEach((e) => {
    Data.affectData.push({
      name: e.name,
      content: e.raw,
      description: null,
      uid: e.uid,
    });
  });
  Data.isDialogShow = false;
};

const onSubmit = async (isNotCheckIn = false) => {
  Data.isNotCheckIn = isNotCheckIn;
  let isCheck = true;
  // if (info.fileType === undefined) return window.$message.warning('请选择文档大类');
  /**判断项目编号是否是当前库 */
  // if (Data.submitData['ProjectNumber']) {
  //   await $api.createApi.checkPorjcetNumber({ newNum: Data.submitData['ProjectNumber'] }).then((res) => {
  //     if (res.success) {
  //       /**
  //        * res.msg === 'false' 嵌入式软件库
  //        * res.msg === 'true' 系统软件库
  //        * res.msg === '不存在' 项目编号不存在
  //        */
  //       if (res.msg === '不存在' || (res.msg === 'false' && route.query.type === 'systemSoft') || (res.msg === 'true' && route.query.type === 'embeddedSoftware')) {
  //         isCheck = false;
  //         window.$message.warning(res.msg === '不存在' ? '项目编号不存在，请重新输入！' : '项目编号不匹配，请重新输入！');
  //       }
  //     }
  //   });
  // }
  // if (!isCheck) return;
  // if (!Data.contentFile.length) return window.$message.warning('请上传文件');
  form.value.ruleForm.validate(async (valid, fields) => {
    if (valid) {
      let formData = new FormData();
      let params = {
        oid: Data.containerOid,
        type: info.fileType,
        attrs: Data.submitData,
        secondarys: [],
      };
      formData.append('serviceKey', 'wt.doc.WTDocument');
      if (Data.contentFile.length > 0 && Data.contentFile[0].raw) {
        formData.append('primary', Data.contentFile[0].raw);
      } else if (Data.contentFile.length > 0 && Data.contentFile[0].oid) {
        // params.filesForm.primaryOid = Data.contentFile[0].oid;
      }
      Data.affectData.forEach((e) => {
        e.oid && params.secondarys.push(e.oid);
        // params.filesForm.secondaryInfo[`${e.name}_description`] = e.description;
        e.content && formData.append(`secondary`, e.content);
      });
      if (!route.query.oid) {
        formData.append('params', JSON.stringify(params));
        $api.documentApi.createDoc(formData).then((res) => {
          if (res.success === true) {
            // window.$message.success('创建成功');
            ElNotification({
              title: '创建成功',
              dangerouslyUseHTMLString: true,
              message: `<span>已经成功创建对象：</span><span id="createJump" style="color:#0062FF;cursor: pointer">${Data.submitData.name}</span>`,
              type: 'success',
            });
            const createJump = document.getElementById('createJump');
            let routeEntry = route.query.entry;
            createJump.onclick = () => {
              router.push({
                name: routeEntry ? 'systemSoftManageDetail' : 'systemSoftDetail',
                query: {
                  model: 'file',
                  type: 'system', //嵌入式软件&系统软件类型（供操作的hooks用）
                  oid: res.data,
                },
              });
            };
            goback();
          } else {
            window.$message.error(res.message);
          }
        });
      } else {
        params.oid = route.query.oid;
        params.notCheckIn = Data.isNotCheckIn;
        formData.append('params', JSON.stringify(params));
        $api.documentApi.editDoc(formData).then((res) => {
          if (res.success === true) {
            window.$message.success('编辑成功');
            !Data.isNotCheckIn && goback();
          } else {
            window.$message.error(res.message);
          }
        });
      }
    } else {
      form.value.checkForm(valid, fields);
    }
  });
};

//返回
const goback = () => {
  history.back();
  sessionStorage.setItem('activeFlag', true);
};

// 选择大类，获取文档属性布局
const getFileType = (val) => {
  initFun(val);
};
const clearData = () => {
  Data.formList = [];
  Data.submitData = {};
  info.fileType = undefined;
  Data.fileTypeList = [];
  Data.affectData = [];
  Data.contentFile = [];
  Data.selectFiles = [];
  Data.fileList = [];
};
</script>
<style lang="less" scoped>
.depart {
  & + .depart {
    margin-top: 20px;
  }
  .title {
    font-size: 16px;
    font-weight: bolder;
    border-left: 3px solid var(--el-color-primary);
    padding-left: 10px;
    margin-bottom: 12px;
  }
  .btn_box {
    margin-bottom: 12px;
  }
  .tip {
    display: flex;
    color: red;
    border: 1px dashed red;
    padding: 5px 12px;
    align-items: center;
    margin-bottom: 10px;
    background-color: #fff0f0;
    span {
      color: #fff;
      width: 18px;
      height: 18px;
      display: flex;
      background-color: red;
      border-radius: 50%;
      margin-right: 10px;
      align-items: center;
      justify-content: center;
    }
  }
}
.footer {
  position: absolute;
  width: 100%;
  left: 0px;
  bottom: 0px;
  box-shadow: 0px -1px 5px 0 rgba(0, 0, 0, 0.08);
  z-index: 3;
  .actionRow {
    text-align: right;
    background: #fff;
    padding: 16px 20px 16px 0;
  }
}
</style>
